import { Body, Controller, Get, HttpException, HttpStatus, Inject, Post } from '@nestjs/common';
import { ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import { LantUtil } from '../../../utils/lant.util';
import { BoolResDto } from '../../common/dtos/bool.res.dto';
import { ConfigProvider } from '../../config/constants/config.constant';
import { ConfigService } from '../../config/services/config.service';
import { LogAppender } from '../../log/constants/log.constant';
import { LogService } from '../../log/services/log.service';
import { GeetestRegisterResDto } from '../dtos/geetest.register.res.dto';
import { GeetestValidateReqDto } from '../dtos/geetest.validate.req.dto';
const Geetest = require('geetest');

@ApiTags('geetest')
@Controller('geetest')
export class GeetestController {
  constructor(
    @Inject(ConfigProvider)
    private readonly configService: ConfigService,
    private readonly logService: LogService,
    private readonly lantUtil: LantUtil
  ) {}

  @ApiOperation({ summary: '验证初始化接口' })
  @ApiOkResponse({ description: '返回初始化接口验证结果', type: GeetestRegisterResDto })
  @Get('register')
  async register(): Promise<GeetestRegisterResDto> {
    try {
      const captcha = new Geetest({
        geetest_id: this.configService.geetest.id,
        geetest_key: this.configService.geetest.key
      });

      return captcha.register();
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.error(LogAppender.geetest, `Cannot register geetest, the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @ApiOperation({ summary: '二次验证接口' })
  @ApiOkResponse({ description: '返回二次验证接口结果', type: BoolResDto })
  @Post('validate')
  async validate(@Body() body: GeetestValidateReqDto): Promise<BoolResDto> {
    try {
      const captcha = new Geetest({
        geetest_id: this.configService.geetest.id,
        geetest_key: this.configService.geetest.key
      });

      const result = await captcha.validate({
        challenge: body.geetest_challenge,
        validate: body.geetest_validate,
        seccode: body.geetest_seccode
      });

      return { result: result };
    } catch (error) {
      if (error instanceof HttpException) throw error;
      this.logService.error(LogAppender.geetest, `Cannot validate geetest by ${JSON.stringify(body)}, the error is ${error}`, this.lantUtil.parseError(error));
      throw new HttpException(error, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }
}
